# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
# pure python port by Brett Hartshorn 2012
# requires: http://code.google.com/p/pyev-ctypes/

#cimport cython
#cimport libev
#from python cimport *
import os, sys, traceback, ctypes
import signal as signalmodule

sys.path.append('../../pyev-ctypes')
import libev

__all__ = ['get_version',
           'get_header_version',
           'supported_backends',
           'recommended_backends',
           'embeddable_backends',
           'time',
           'loop']

# callbacks.h just has some macros that wrap for errors
# instead just pass user function directly using ctypes
'''
cdef extern from "callbacks.h":
    void gevent_callback_io(libev.ev_loop, void*, int)
    void gevent_callback_timer(libev.ev_loop, void*, int)
    void gevent_callback_signal(libev.ev_loop, void*, int)
    void gevent_callback_idle(libev.ev_loop, void*, int)
    void gevent_callback_prepare(libev.ev_loop, void*, int)
    void gevent_callback_fork(libev.ev_loop, void*, int)
    void gevent_callback_async(libev.ev_loop, void*, int)
    void gevent_callback_child(libev.ev_loop, void*, int)
    void gevent_callback_stat(libev.ev_loop, void*, int)
    void gevent_signal_check(libev.ev_loop, void*, int)
    void gevent_periodic_signal_check(libev.ev_loop, void*, int)

cdef extern from *:
    int errno

cdef extern from "stathelper.c":
    object _pystat_fromstructstat(void*)

'''



UNDEF = libev.EV_UNDEF
NONE = libev.EV_NONE
READ = libev.EV_READ
WRITE = libev.EV_WRITE
TIMER = libev.EV_TIMER
PERIODIC = libev.EV_PERIODIC
SIGNAL = libev.EV_SIGNAL
CHILD = libev.EV_CHILD
STAT = libev.EV_STAT
IDLE = libev.EV_IDLE
PREPARE = libev.EV_PREPARE
CHECK = libev.EV_CHECK
EMBED = libev.EV_EMBED
FORK = libev.EV_FORK
CLEANUP = libev.EV_CLEANUP
ASYNC = libev.EV_ASYNC
CUSTOM = libev.EV_CUSTOM
ERROR = libev.EV_ERROR

READWRITE = libev.EV_READ | libev.EV_WRITE

MINPRI = libev.EV_MINPRI
MAXPRI = libev.EV_MAXPRI

BACKEND_PORT = libev.EVBACKEND_PORT
BACKEND_KQUEUE = libev.EVBACKEND_KQUEUE
BACKEND_EPOLL = libev.EVBACKEND_EPOLL
BACKEND_POLL = libev.EVBACKEND_POLL
BACKEND_SELECT = libev.EVBACKEND_SELECT
FORKCHECK = libev.EVFLAG_FORKCHECK
NOINOTIFY = libev.EVFLAG_NOINOTIFY
SIGNALFD = libev.EVFLAG_SIGNALFD
NOSIGMASK = libev.EVFLAG_NOSIGMASK

'''
@cython.internal
cdef class _EVENTSType:

    def __repr__(self):
        return 'gevent.core.EVENTS'


cdef public object GEVENT_CORE_EVENTS = _EVENTSType()
EVENTS = GEVENT_CORE_EVENTS
'''
class _EVENTSType(object):
    def __repr__(self):
        return 'gevent.core.EVENTS'
GEVENT_CORE_EVENTS = _EVENTSType()
EVENTS = GEVENT_CORE_EVENTS


def get_version():
    return 'libev-%d.%02d' % (libev.ev_version_major(), libev.ev_version_minor())


def get_header_version():
    return 'libev-%d.%02d' % (libev.EV_VERSION_MAJOR, libev.EV_VERSION_MINOR)


# This list backends in the order they are actually tried by libev
_flags = [(libev.EVBACKEND_PORT, 'port'),
          (libev.EVBACKEND_KQUEUE, 'kqueue'),
          (libev.EVBACKEND_EPOLL, 'epoll'),
          (libev.EVBACKEND_POLL, 'poll'),
          (libev.EVBACKEND_SELECT, 'select'),
          (libev.EVFLAG_NOENV, 'noenv'),
          (libev.EVFLAG_FORKCHECK, 'forkcheck'),
          (libev.EVFLAG_SIGNALFD, 'signalfd'),
          (libev.EVFLAG_NOSIGMASK, 'nosigmask')]


_flags_str2int = dict((string, flag) for (flag, string) in _flags)


_events = [(libev.EV_READ,     'READ'),
           (libev.EV_WRITE,    'WRITE'),
           (libev.EV__IOFDSET, '_IOFDSET'),
           (libev.EV_PERIODIC, 'PERIODIC'),
           (libev.EV_SIGNAL,   'SIGNAL'),
           (libev.EV_CHILD,    'CHILD'),
           (libev.EV_STAT,     'STAT'),
           (libev.EV_IDLE,     'IDLE'),
           (libev.EV_PREPARE,  'PREPARE'),
           (libev.EV_CHECK,    'CHECK'),
           (libev.EV_EMBED,    'EMBED'),
           (libev.EV_FORK,     'FORK'),
           (libev.EV_CLEANUP,  'CLEANUP'),
           (libev.EV_ASYNC,    'ASYNC'),
           (libev.EV_CUSTOM,   'CUSTOM'),
           (libev.EV_ERROR,    'ERROR')]


def _flags_to_list( flags ):
    result = []
    for code, value in _flags:
        if flags & code:
            result.append(value)
        flags &= ~code
        if not flags:
            break
    if flags:
        result.append(flags)
    return result


if sys.version_info[0] >= 3:
    basestring = (bytes, str)
else:
    basestring = (str,unicode)    #__builtins__.basestring

def _flags_to_int(flags):
    # Note, that order does not matter, libev has its own predefined order
    if not flags:
        return 0
    if isinstance(flags, (int, long)):
        return flags
    result = 0
    try:
        if isinstance(flags, basestring):
            flags = flags.split(',')
        for value in flags:
            value = value.strip().lower()
            if value:
                result |= _flags_str2int[value]
    except KeyError, ex:
        raise ValueError('Invalid backend or flag: %s\nPossible values: %s' % (ex, ', '.join(sorted(_flags_str2int.keys()))))
    return result


def _str_hex(flag):
    if isinstance(flag, (int, long)): return hex(flag)
    else: return str(flag)


def _check_flags(flags):
    flags &= libev.EVBACKEND_MASK
    if not flags:
        return
    if not (flags & libev.EVBACKEND_ALL):
        raise ValueError('Invalid value for backend: 0x%x' % flags)
    if not (flags & libev.ev_supported_backends()):
        as_list = [_str_hex(x) for x in _flags_to_list(flags)]
        raise ValueError('Unsupported backend: %s' % '|'.join(as_list))


def _events_to_str(events):
    result = []
    for (flag, string) in _events:
        c_flag = flag
        if events & c_flag:
            result.append(string)
            events = events & (~c_flag)
        if not events:
            break
    if events:
        result.append(hex(events))
    return '|'.join(result)


def supported_backends():
    return _flags_to_list(libev.ev_supported_backends())


def recommended_backends():
    return _flags_to_list(libev.ev_recommended_backends())


def embeddable_backends():
    return _flags_to_list(libev.ev_embeddable_backends())


def time():
    return libev.ev_time()


_default_loop_destroyed = False

class loop(object):     # [object PyGeventLoopObject, type PyGeventLoop_Type]:
#    cdef libev.ev_loop* _ptr
#    cdef public object error_handler
#    cdef libev.ev_prepare _signal_checker
#ifdef _WIN32
#    cdef libev.ev_timer _periodic_signal_checker
#endif

    _ptr = None
    error_handler = None
    _signal_checker = None

    def __init__(self, flags=None, default=True, ptr=0):
        #cdef unsigned int c_flags
        old_handler = None

## this signal check only calls: PyErr_CheckSignals(); and if (PyErr_Occurred()) gevent_handle_error ##
#        libev.ev_prepare_init(&self._signal_checker, <void*>gevent_signal_check)
#ifdef _WIN32
#        libev.ev_timer_init(&self._periodic_signal_checker, <void*>gevent_periodic_signal_check, 0.3, 0.3)
#endif

        if ptr:
            self._ptr = ptr
        else:
            c_flags = _flags_to_int(flags)
            _check_flags(c_flags)
            c_flags |= libev.EVFLAG_NOENV
            if _default_loop_destroyed:
                default = False
            if default:
                self._ptr = libev.ev_default_loop(c_flags)
                if not self._ptr:
                    raise SystemError("ev_default_loop(%s) failed" % (c_flags, ))
                #libev.ev_prepare_start(self._ptr, &self._signal_checker)
                libev.ev_unref(self._ptr)
#ifdef _WIN32
#                libev.ev_timer_start(self._ptr, &self._periodic_signal_checker)
#                libev.ev_unref(self._ptr)
#endif
            else:
                self._ptr = libev.ev_loop_new(c_flags)
                if not self._ptr:
                    raise SystemError("ev_loop_new(%s) failed" % (c_flags, ))

            #if default or __SYSERR_CALLBACK is None:
            #    set_syserr_cb(self._handle_syserr)

    def _stop_signal_checker(self):
        '''
        if libev.ev_is_active(&self._signal_checker):
            libev.ev_ref(self._ptr)
            libev.ev_prepare_stop(self._ptr, &self._signal_checker)
#ifdef _WIN32
        if libev.ev_is_active(&self._periodic_signal_checker):
            libev.ev_ref(self._ptr)
            libev.ev_timer_stop(self._ptr, &self._periodic_signal_checker)
#endif
        '''
        return

    def destroy(self):
        global _default_loop_destroyed
        if self._ptr:
            self._stop_signal_checker()
            if __SYSERR_CALLBACK == self._handle_syserr:
                set_syserr_cb(None)
            if libev.ev_is_default_loop(self._ptr):
                _default_loop_destroyed = True
            libev.ev_loop_destroy(self._ptr)
            self._ptr = NULL

    def __dealloc__(self):  # this should be __del__ TODO
        if self._ptr:
            self._stop_signal_checker()
            if not libev.ev_is_default_loop(self._ptr):
                libev.ev_loop_destroy(self._ptr)
            self._ptr = NULL

    @property
    def ptr(self): return self._ptr
    @property
    def WatcherType(self): return watcher   # returns abstract base class
    @property
    def MAXPRI(self): return libev.EV_MAXPRI
    @property
    def MINPRI(self): return libev.EV_MINPRI

    def _handle_syserr(self, message, errno):
        #self.handle_error(None, SystemError, SystemError(message + ': ' + os.strerror(errno)), None)
        raise SystemError(  os.strerror(errno ) )

    '''
    cpdef handle_error(self, context, type, value, tb):
        cdef object handle_error
        cdef object error_handler = self.error_handler
        if error_handler is not None:
            # we do want to do getattr every time so that setting Hub.handle_error property just works
            handle_error = getattr(error_handler, 'handle_error', error_handler)
            handle_error(context, type, value, tb)
        else:
            self._default_handle_error(context, type, value, tb)

    cpdef _default_handle_error(self, context, type, value, tb):
        # note: Hub sets its own error handler so this is not used by gevent
        # this is here to make core.loop usable without the rest of gevent
        import traceback
        traceback.print_exception(type, value, tb)
        libev.ev_break(self._ptr, libev.EVBREAK_ONE)
    '''

    def run(self, nowait=False, once=False):
        flags = 0
        if nowait:
            flags |= libev.EVRUN_NOWAIT
        if once:
            flags |= libev.EVRUN_ONCE

        ## run libev main loop - ctypes will release the GIL ##
        libev.ev_run(self._ptr, flags)
        print('LIBEV main loop exit')

    def reinit(self):
        libev.ev_loop_fork(self._ptr)

    def ref(self):
        libev.ev_ref(self._ptr)

    def unref(self):
        libev.ev_unref(self._ptr)

    def break_(self, how=libev.EVBREAK_ONE):
        libev.ev_break(self._ptr, how)

    def verify(self):
        libev.ev_verify(self._ptr)

    def now(self):
        return libev.ev_now(self._ptr)

    def update(self):
        libev.ev_now_update(self._ptr)

    def __repr__(self):
        return '<%s at 0x%x %s>' % (self.__class__.__name__, id(self), self._format())

    @property
    def default(self): return True if libev.ev_is_default_loop(self._ptr) else False

    @property
    def iteration(self): return libev.ev_iteration(self._ptr)

    @property
    def depth(self): return libev.ev_depth(self._ptr)

    @property
    def backend_int(self): return libev.ev_backend(self._ptr)

    @property
    def backend(self):
        backend = libev.ev_backend(self._ptr)
        for key, value in _flags:
            if key == backend:
                return value
        return backend

    @property
    def pendingcnt(self): return libev.ev_pending_count(self._ptr)

    def io(self, fd, events, ref=True, priority=None):
        return io(self, fd, events, ref, priority)

    def timer(self, after, repeat=0.0, ref=True, priority=None):
        return timer(self, after, repeat, ref, priority)

    def signal(self, signum, ref=True, priority=None):
        return signal(self, signum, ref, priority)

    def idle(self, ref=True, priority=None):
        return idle(self, ref, priority)

    def prepare(self, ref=True, priority=None):
        return prepare(self, ref, priority)

    def fork(self, ref=True, priority=None):
        return fork(self, ref, priority)

    def async(self, ref=True, priority=None):
        return async(self, ref, priority)

#if EV_CHILD_ENABLE

    def child(self, pid, trace=0, ref=True):
        return child(self, pid, trace, ref)

    def install_sigchld(self):
        libev.gevent_install_sigchld_handler()

#endif

    def stat(self, path, interval=0.0, ref=True, priority=None):
        return stat(self, path, interval, ref, priority)

    def callback(self, priority=None):
        return callback(self, priority=priority)

    def run_callback(self, func, *args, **kw):
        result = callback(self, priority=kw.get('priority'))
        result.start(func, *args)
        return result

    def _format(self):
        msg = self.backend
        if self.default:
            msg += ' default'
        msg += ' pending=%s' % self.pendingcnt
        msg += self._format_details()
        return msg

    def _format_details(self):
        msg = ''
        fileno = self.fileno()
        sigfd = None
        activecnt = None
        try:
            sigfd = self.sigfd
        except AttributeError:
            sigfd = None
        try:
            activecnt = self.activecnt
        except AttributeError:
            pass
        if activecnt is not None:
            msg += ' ref=' + repr(activecnt)
        if fileno is not None:
            msg += ' fileno=' + repr(fileno)
        if sigfd is not None and sigfd != -1:
            msg += ' sigfd=' + repr(sigfd)
        return msg

    def fileno(self):
        fd = self._ptr.backend_fd
        if fd >= 0: return fd

    @property
    def activecnt(self): return self._ptr.activecnt
    @property
    def sigfd(self): return self._ptr.sigfd

    @property
    def origflags(self): return _flags_to_list(self._ptr.origflags)

    @property
    def origflags_int(self): return self._ptr.origflags

#endif


#define PYTHON_INCREF if not self._flags & 1:  \
#            Py_INCREF(<PyObjectPtr>self)       \
#            self._flags |= 1

#define LIBEV_UNREF if self._flags & 6 == 4:   \
#            libev.ev_unref(self.loop._ptr)     \
#            self._flags |= 2

# about readonly _flags attribute:
# bit #1 set if object owns Python reference to itself (Py_INCREF was called and we must call Py_DECREF later)
# bit #2 set if ev_unref() was called and we must call ev_ref() later
# bit #3 set if user wants to call ev_unref() before start()
'''
#define WATCHER_BASE(TYPE)                                                              \
    cdef public loop loop                                                               \
    cdef object _callback                                                               \
    cdef public tuple args                                                              \
    cdef readonly int _flags                                                            \
    cdef libev.ev_##TYPE _watcher                                                       \
                                                                                        \
    property ref:                                                                       \
                                                                                        \
        def __get__(self):                                                              \
            return False if self._flags & 4 else True                                   \
                                                                                        \
        def __set__(self, object value):                                                \
            if value:                                                                   \
                if not self._flags & 4:                                                 \
                    return  # ref is already True                                       \
                if self._flags & 2:  # ev_unref was called, undo                        \
                    libev.ev_ref(self.loop._ptr)                                        \
                self._flags &= ~6  # do not want unref, no outstanding unref            \
            else:                                                                       \
                if self._flags & 4:                                                     \
                    return  # ref is already False                                      \
                self._flags |= 4                                                        \
                if not self._flags & 2 and libev.ev_is_active(&self._watcher):          \
                    libev.ev_unref(self.loop._ptr)                                      \
                    self._flags |= 2                                                    \
                                                                                        \





'''

####################################

class watcher(object):
    """Abstract base class for all the watchers"""
    TYPE = None

    def _callback_wrapper( self, loop, watcher, revents ):
        print('--------------callback wrapper', loop, watcher, revents)
        print(self.callback, self.args)

    def _init_watcher(self):
        assert self.TYPE
        self.__watcher__ = getattr(libev, 'ev_%s'%self.TYPE)()
        self._watcher = ctypes.pointer( self.__watcher__ )


    def __init__(self, loop, *args, **kw):
        self._init_watcher()
        self.loop = loop

        init = getattr(libev,'ev_%s_init'%self.TYPE)
        if args:
            init( self.__watcher__, self._callback_wrapper, *args )
        else:
            init( self.__watcher__, self._callback_wrapper )

        if kw.get('ref'): self._flags = 0
        else: self._flags = 4
        if kw.get('priority'):
            libev.ev_set_priority( self._watcher, kw['priority'] )

    @property   # default pending - only async overrides this
    def pending(self): return True if libev.ev_is_pending(self._watcher) else False

    def start(self, callback, *args):
        print('_______starting', callback, args)
        self.callback = callback
        self.args = args
        #LIBEV_UNREF                                              \
        func = getattr(libev,'ev_%s_start'%self.TYPE)
        func(self.loop._ptr, self._watcher)
        #PYTHON_INCREF

    @property
    def active(self): return True if libev.ev_is_active(self._watcher) else False


    def __repr__(self):
        format = self._format()
        result = "<%s at 0x%x%s" % (self.__class__.__name__, id(self), format)
        if self.active:
            result += " active"
        if self.pending:
            result += " pending"
        if self.callback is not None:
            result += " callback=%r" % (self.callback, )
        if self.args is not None:
            result += " args=%r" % (self.args, )
        return result + ">"

    def _format(self):
        return ''


    def feed(self, revents, callback, *args):
        print('*************feeding',callback,args)
        self.callback = callback
        self.args = args
        #LIBEV_UNREF                                                                     
        libev.ev_feed_event(self.loop._ptr, self._watcher, revents)
        #PYTHON_INCREF

    def __get__(self): return libev.ev_priority(self._watcher)
    def __set__(self, priority):
        if libev.ev_is_active(self._watcher):
            raise AttributeError("Cannot set priority of an active watcher")
        libev.ev_set_priority(self._watcher, priority)
    priority = property( __get__, __set__ )

    def stop(self):  
        if self._flags & 2:                            
            libev.ev_ref(self.loop._ptr)  
            self._flags &= ~2
        func = getattr( libev, 'ev_%s_stop'%self.TYPE )
        func(self.loop._ptr, self._watcher)   
        self._callback = None
        self.args = None
        if self._flags & 1:
            #Py_DECREF(<PyObjectPtr>self)
            self._flags &= ~1


    def __get__(self): return self._callback
    def __set__(self, callback):
        print('----------setting callback', callback)
        #if not PyCallable_Check(<PyObjectPtr>callback):
        #    raise TypeError("Expected callable, not %r" % (callback, ))
        self._callback = callback
    def __del__(self): self._callback = None
    callback = property( __get__, __set__, __del__ )


class io(watcher):
    TYPE = 'io'
    #WATCHER_BASE(io)

    def start(self, callback, *args, **kw):
        self.callback = callback
        if kw.get('pass_events'):
            self.args = (GEVENT_CORE_EVENTS, ) + args
        else:
            self.args = args
        #LIBEV_UNREF
        libev.ev_io_start(self.loop._ptr, self._watcher)
        #PYTHON_INCREF

    #ACTIVE

    #PENDING


    def __init__(self, loop, fd, events, ref=True, priority=None):
        self._init_watcher()
        if fd < 0:  # this was not checked on win32
            raise ValueError('fd must be non-negative: %r' % fd)
        if events & ~(libev.EV__IOFDSET | libev.EV_READ | libev.EV_WRITE):
            raise ValueError('illegal event mask: %r' % events)
        libev.ev_io_init(self._watcher, self._callback_wrapper, fd, events)
        self.loop = loop
        if ref: self._flags = 0
        else: self._flags = 4
        if priority is not None:
            libev.ev_set_priority(self._watcher, priority)

    def __get__(self): return libev.vfd_get(self._watcher.fd)
    def __set__(self, fd):
        if libev.ev_is_active(self._watcher):
            raise AttributeError("'io' watcher attribute 'fd' is read-only while watcher is active")
        vfd = libev.vfd_open(fd)
        libev.vfd_free(self._watcher.fd)
        libev.ev_io_init(self._watcher, gevent_callback_io, vfd, self._watcher.events)
    fd = property( __get__, __set__ )

    def __get__(self): return self._watcher.events
    def __set__(self, events):
        if libev.ev_is_active(self._watcher):
            raise AttributeError("'io' watcher attribute 'events' is read-only while watcher is active")
        libev.ev_io_init(self._watcher, gevent_callback_io, self._watcher.fd, events)
    events = property( __get__, __set__ )

    @property
    def events_str(self): return _events_to_str(self._watcher.events)

    def _format(self):
        return ' fd=%s events=%s' % (self.fd, self.events_str)

#ifdef _WIN32
#
#    def __cinit__(self):
#        self._watcher.fd = -1;
#
#    def __dealloc__(self):
#        libev.vfd_free(self._watcher.fd)
#
#endif


class timer(watcher):   # [object PyGeventTimerObject, type PyGeventTimer_Type]:
    TYPE = 'timer'
    #WATCHER_BASE(timer)

    def start(self, callback, *args, **kw):
        self.callback = callback
        self.args = args
        #LIBEV_UNREF
        if kw.get('update'):
            libev.ev_now_update(self.loop._ptr)
        libev.ev_timer_start(self.loop._ptr, self._watcher)
        #PYTHON_INCREF

    #ACTIVE

    #PENDING

    def __init__(self, loop, after=0.0, repeat=0.0, ref=True, priority=None):
        self._init_watcher()
        self.loop = loop

        if repeat < 0.0:
            raise ValueError("repeat must be positive or zero: %r" % repeat)
        libev.ev_timer_init(self._watcher, self._callback_wrapper, after, repeat)
        if ref: self._flags = 0
        else: self._flags = 4
        if priority is not None:
            libev.ev_set_priority(self._watcher, priority)

    @property
    def at(self): return self._watcher.at

    # QQQ: add 'after' and 'repeat' properties?

    def again(self, callback, *args, **kw):
        self.callback = callback
        self.args = args
        #LIBEV_UNREF
        if kw.get('update', True):
            libev.ev_now_update(self.loop._ptr)
        libev.ev_timer_again(self.loop._ptr, self._watcher)
        #PYTHON_INCREF


class signal(watcher):
    TYPE = 'signal'
    #WATCHER(signal)

    def __init__(self, loop, signalnum, ref=True, priority=None):
        if signalnum < 1 or signalnum >= signalmodule.NSIG:
            raise ValueError('illegal signal number: %r' % signalnum)
        # still possible to crash on one of libev's asserts:
        # 1) "libev: ev_signal_start called with illegal signal number"
        #    EV_NSIG might be different from signal.NSIG on some platforms
        # 2) "libev: a signal must not be attached to two different loops"
        #    we probably could check that in LIBEV_EMBED mode, but not in general
        libev.ev_signal_init(self._watcher, gevent_callback_signal, signalnum)
        self.loop = loop
        if ref:
            self._flags = 0
        else:
            self._flags = 4
        if priority is not None:
            libev.ev_set_priority(self._watcher, priority)


class idle(watcher):
    TYPE = 'idle'
#    WATCHER(idle)
#    INIT(idle,,)


class prepare(watcher):
    TYPE = 'prepare'
#    WATCHER(prepare)
#    INIT(prepare,,)


class fork(watcher):
    TYPE = 'fork'
#    WATCHER(fork)
#    INIT(fork,,)


class async(watcher):
    TYPE = 'async'
#    WATCHER_BASE(async)
#    START(async)
#    ACTIVE

    @property
    def pending(self): return True if libev.ev_async_pending(self._watcher) else False

#    INIT(async,,)

    def send(self):
        libev.ev_async_send(self.loop._ptr, self._watcher)


class child(watcher):
    TYPE = 'child'
    #WATCHER(child)

    def __init__(self, loop, pid, trace=0, ref=True):
        self._init_watcher()
        self.loop = loop

        if not loop.default:
            raise TypeError('child watchers are only available on the default loop')
        #libev.gevent_install_sigchld_handler()
        libev.ev_install_sigchld_handler()
        libev.ev_child_init(self._watcher, gevent_callback_child, pid, trace)
        if ref: self._flags = 0
        else: self._flags = 4

    def _format(self):
        return ' pid=%r rstatus=%r' % (self.pid, self.rstatus)

    @property
    def pid(self): return self._watcher.pid

    def __get__(self): return self._watcher.rpid
    def __set__(self, value): self._watcher.rpid = value
    rpid = property( __get__, __set__ )

    def __get__(self): return self._watcher.rstatus
    def __set__(self, value): self._watcher.rstatus = value
    rstatus = property( __get__, __set__ )



class stat(watcher):
    TYPE = 'stat'
    #WATCHER(stat)
    #cdef readonly bytes path

    def __init__(self, loop, path, interval=0.0, ref=True, priority=None):
        self._init_watcher()
        self.loop = loop
        self.path = path

        libev.ev_stat_init(self._watcher, gevent_callback_stat, self.path, interval)
        if ref: self._flags = 0
        else: self._flags = 4
        if priority is not None:
            libev.ev_set_priority(self._watcher, priority)

    @property
    def attr(self):
        if not self._watcher.attr.st_nlink: return
        else: return _pystat_fromstructstat(self._watcher.attr)

    @property
    def prev(self):
        if not self._watcher.prev.st_nlink: return
        else: return _pystat_fromstructstat(self._watcher.prev)

    @property
    def interval(self): return self._watcher.interval


class callback(watcher):
    """Pseudo-watcher used to execute a callback in the loop as soon as possible."""

    # does not matter which type we actually use, since we are going to feed() events, not start watchers
    TYPE = 'prepare'
    #WATCHER_BASE(prepare)

    #INIT(prepare,,)

    def start(self, callback, *args):
        self.callback = callback
        self.args = args
        libev.ev_feed_event(self.loop._ptr, self._watcher, libev.EV_CUSTOM)
        #PYTHON_INCREF

    @property
    def active(self): return self.callback is not None

    #PENDING

'''
__SYSERR_CALLBACK = None

def _syserr_cb(msg):
    try:
        __SYSERR_CALLBACK(msg, errno)
    except:
        set_syserr_cb(None)
        print_exc = getattr(traceback, 'print_exc', None)
        if print_exc is not None:
            print_exc()

def set_syserr_cb(callback):
    print('-------this should be called?')
    global __SYSERR_CALLBACK
    if callback is None:
        libev.ev_set_syserr_cb(NULL)
        __SYSERR_CALLBACK = None
    elif hasattr(callback, '__call__'):
        libev.ev_set_syserr_cb( _syserr_cb )
        __SYSERR_CALLBACK = callback
    else:
        raise TypeError('Expected callable or None, got %r' % (callback, ))
'''

LIBEV_EMBED = True
EV_USE_FLOOR = libev.EV_USE_FLOOR
EV_USE_CLOCK_SYSCALL = libev.EV_USE_CLOCK_SYSCALL
EV_USE_REALTIME = libev.EV_USE_REALTIME
EV_USE_MONOTONIC = libev.EV_USE_MONOTONIC
EV_USE_NANOSLEEP = libev.EV_USE_NANOSLEEP
EV_USE_INOTIFY = libev.EV_USE_INOTIFY
EV_USE_SIGNALFD = libev.EV_USE_SIGNALFD
EV_USE_EVENTFD = libev.EV_USE_EVENTFD
EV_USE_4HEAP = libev.EV_USE_4HEAP

